<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller{

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
    {
        parent::__construct();
		$this->load->library('session');
		$this->load->database();
		$this->load->helper('captcha');
		$this->load->helper('url');
	}
	
	public function index(){
		$this->load->view('login');
	}
	
	//用户登录
	public function logining()		
	{
		if($this->input->post('captcha') == $this->session->userdata('word')){
			$this->load->model('user');		
			$info = $this->user->get_userinfo($this->input->post('username'),$this->input->post('password'));
			if($info){			
				$info['power'] = $this->user->get_userpower($info['departid'], $info['id']);
				
				$arr = array('user'=>$info['username'],'userid'=>$info['id'],'userpower'=>$info['power']);
				
				$this->session->set_userdata($arr);		
				if($this->session->userdata("user")){
					header('Location: /index.php/');
				}
			}else{
				header("Content-Type:text/html;charset=utf-8");
				echo "<script>alert('用户名或密码错误');history.go(-1);</script>";
			}	
		}else{
			header("Content-Type:text/html;charset=utf-8");
			echo "<script>alert('请输入正确的验证码');history.go(-1);</script>";
		}
	}
	//退出
	function loginout(){
		$this->load->library('session');
		$this->session->unset_userdata("user");
		$this->session->unset_userdata("userid");
		$this->session->unset_userdata("userpower");
		header('Location: /index.php/login');
		
	}
	//验证码
	 public function get_captcha()
    {

	   if ($this->input->is_ajax_request()) {
            $this->load->helper('captcha');
            $vals=array(
				'word'=>rand(1000,10000),
				'img_path'=>'./captcha/',
				'img_url'=>base_url()."captcha/",
				'img_width'=>'80',
				'img_height'=>'30',
				'expiration'=>5
                        );	
            $cap = create_captcha($vals);
			$data = array('word' => $cap['word']);
			$this->session->set_userdata($data);
            echo $cap['image'];
        } else {
            show_404();
        }
    }
	
	
}

/*
	
	$arr = array('username'=>'admin','password'=>md5('admin'),'roleid'=>1);
		$this->admin->insert_userinfo($arr);*/